package com.ttai.presenter.base;

import com.google.gson.JsonArray;
import com.ttai.model.net.ArrayInfo;
import com.ttai.presenter.api.ResponseInfoApi;
import com.ttai.untils.Constant;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public abstract class BaseArrayPresenter {
    public ResponseInfoApi responseInfoApi;
    public Retrofit retrofit;

    //网络请求
    public BaseArrayPresenter() {


        //1.初始化retrofit对象
        //2.指定了访问服务器工程的主机名
        if (responseInfoApi == null) {
            retrofit = new Retrofit.Builder().
                    baseUrl(Constant.BASE_URL).
                    addConverterFactory(GsonConverterFactory.create()).
                    build();
        }
        //3.指定具体的网络请求实体对象
        //发送一个网络请求(完整的链接地址,请求方式(GET POST),请求过程中参数,请求的响应结果)
        responseInfoApi = retrofit.create(ResponseInfoApi.class);
    }
    public class CallBackArrayAdapter implements Callback<ArrayInfo> {
        @Override
        public void onResponse(Call<ArrayInfo> call, Response<ArrayInfo> response) {
            ArrayInfo body = response.body();
            try{
                if (body.getCode()==200){
                    parseArray(body.getData());
                }
            }catch (Exception e){

            }

        }

        @Override
        public void onFailure(Call<ArrayInfo> call, Throwable t) {
            if (t instanceof RuntimeException){
                //请求失败
                String message = t.getMessage();
                showError(message);
            }
        }
    }

    protected abstract void parseArray(JsonArray data);
    protected abstract void showError(String message);

}